package com.snail.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.snail.config.WeixinMiniProperties;
import com.snail.constants.RedisConstants;
import com.snail.constants.SystemConstants;
import com.snail.exception.BizException;
import com.snail.model.vo.user.ThirdPartyUserInfoVO;
import com.snail.service.ThirdPartyProviderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Author 蔡徐坤
 * @Date 2025/8/20 11:53
 * @Description: TODO
 */

@Service("weixinMiniProviderService")
@RequiredArgsConstructor
@Slf4j
public class WeixinMiniProviderServiceImpl implements ThirdPartyProviderService {

    // 注入微信小程序的配置
    private final WeixinMiniProperties weixinMiniProperties;

    // 用于发起HTTP请求
    private final RestTemplate restTemplate;

    @Override
    public ThirdPartyUserInfoVO getUserInfoByCode(String provider, String code) {
        // 1. 校验参数
        if (code == null || code.isBlank()) {
            log.error("[微信小程序] code 为空");
            throw new BizException("没有传入code的值");
        }

        // 2. 调用微信接口，用 code 换取 openid 和 session_key
        String url = SystemConstants.CODE_2_SESSION_URL
                .replace("{appid}", weixinMiniProperties.getAppid())
                .replace("{secret}", weixinMiniProperties.getSecret())
                .replace("{code}", code);

        log.info("[微信小程序] 准备调用 code2Session 接口，code: {}", code);
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            String responseBody = response.getBody();
            log.info("[微信小程序] code2Session 接口响应: {}", responseBody);

            // 3. 解析微信返回的JSON
            JSONObject jsonObject = JSONUtil.parseObj(responseBody);
            String openid = jsonObject.getStr("openid");
            String sessionKey = jsonObject.getStr("session_key");
            Integer errcode = jsonObject.getInt("errcode");
            String errmsg = jsonObject.getStr("errmsg");

            // 4. 处理接口调用错误
            if (errcode != null && errcode != 0) {
                log.error("[微信小程序] code2Session 接口调用失败, errcode: {}, errmsg: {}", errcode, errmsg);
                throw new BizException("小程序接口调用失败");
            }

            // 5. 如果openid为空，也认为是失败
            if (openid == null || openid.isBlank()) {
                log.error("[微信小程序] openid 为空");
                throw new BizException("openid 为空");
            }

            // 6. 构建并返回用户信息VO
            ThirdPartyUserInfoVO userInfo = new ThirdPartyUserInfoVO();
            userInfo.setOpenId(openid); // 这里设置的是微信返回的**真实openid**
            userInfo.setProvider(provider);
            userInfo.setNickname("微信用户"); // 默认昵称
            userInfo.setAvatar("http://172.172.2.99:9000/pic/2025/08/19/ab115febdd2f06da6308e8bddfb01edf.jpg"); // 默认头像

            log.info("[微信小程序] 成功获取用户信息, openid: {}", openid);
            return userInfo;

        } catch (Exception e) {
            log.error("[微信小程序] 调用 code2Session 接口时发生异常", e);
            return null;
        }
    }
}
